package com.yx.filter;

import com.alibaba.fastjson.JSONObject;
import com.yx.pojo.LoginUser;
import com.yx.pojo.Result;
import com.yx.utils.JwtUtil;
import com.yx.utils.RedisCache;
import io.jsonwebtoken.Claims;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import java.io.IOException;
import java.util.Objects;

@Slf4j
@WebFilter(urlPatterns = "/*")
@Component
public class LoginCheckFilter implements Filter {

    @Autowired
    private RedisCache redisCache;

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;

        //1.获取请求url
        String url = req.getRequestURL().toString();
        log.info("请求的url：{}",url);

        //2.判断请求url中是否包含login，如果包含，说明是登录操作，放行

        if(url.contains("login")){
            log.info("登录操作，放行");
            chain.doFilter(req,resp);
            return;
        }

        //3.获取请求头中的令牌(token)
        String jwt = req.getHeader("token");
        //4.判断令牌是否存在，如果不存在，返回错误信息（未登录）
        if(!StringUtils.hasLength(jwt)){
            log.info("请求头的token为空，返回未登录的信息");
            Result error = Result.error("NOT_LOGIN");
            // 设置状态码
            resp.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            //手动转换  对象-- json ------->阿里巴巴的fastJSON
            String notLogin = JSONObject.toJSONString(error);
            resp.getWriter().write(notLogin);//返回给前端
            return;
        }

        //5.解析token，如果解析失败，返回错误结果（未登录）。
        String userId;
        try {
            Claims claims = JwtUtil.parseJWT(jwt);
            userId = claims.getSubject();
            log.info("userId:{}",userId);
        } catch (Exception e) {//jwt解析失败
            throw new RuntimeException("token非法");
        }

        //3.在redis中获取用户信息 注意：redis中的key是login：+userId
        String redisKey = "login:" + userId;
        LoginUser loginUser = redisCache.getCacheObject(redisKey);

        //此处需要判断loginUser是否为空
        if (Objects.isNull(loginUser)){
            throw new RuntimeException("用户未登录");
        }
        //4.将获取到的用户信息存入SecurityContextHolder 参数（用户信息，，权限信息）
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);

        //6.放行
        log.info("令牌合法，放行");
        chain.doFilter(req,resp);


    }
}
